package com.ross.web.util;

import java.util.ResourceBundle;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

import com.ross.web.util.Encrypter;

public class HibernateUtil {

	private static SessionFactory sessionFactory = createSessionFactory();

	public static SessionFactory createSessionFactory() {
		// return new Configuration().configure().buildSessionFactory();	
		if (sessionFactory == null) {
			try {
				String baseName = "resources.db_connection";
				ResourceBundle rb = ResourceBundle.getBundle(baseName);
				Encrypter encrypter = new Encrypter();
				Configuration configuration = new Configuration();
				configuration.setProperty("hibernate.connection.url", encrypter.decrypt(rb.getString("database_url")));
				configuration.setProperty("hibernate.connection.username", encrypter.decrypt(rb.getString("username")));
				configuration.setProperty("hibernate.connection.password", encrypter.decrypt(rb.getString("password")));
				configuration.setProperty("hibernate.connection.driver_class", rb.getString("driver"));
				return configuration.configure().buildSessionFactory();
			} catch (Throwable throwable) {
				throwable.printStackTrace();
			}
		}
		return sessionFactory;
	}

	public static Session getSession() {
		return sessionFactory.openSession();
	}
}
